//
//  FQDSearchViewController.m
//  FakeQDaily
//
//  Created by mewxiv on 9/30/16.
//  Copyright © 2016 Xensius. All rights reserved.
//

#import "FQDSearchViewController.h"
#import "FQDArticleDetailViewController.h"
#import "FQDLabVoteDetailViewController.h"
#import "FQDLabOpinionViewController.h"
#import "FQDSearchResultProvider.h"
#import "FQDSearchHeaderView.h"
#import "FQDSearchResultTableViewCell.h"
#import "FQDRefreshFooter.h"
#import "FQDBlurView.h"
#import "FQDRestModel.h"
#import "FQDLabFeedCellItem.h"
#import "QDailyAPI.h"

#import "Masonry.h"

@interface FQDSearchViewController () <UISearchBarDelegate, UIScrollViewDelegate,
                                       UITableViewDataSource, UITableViewDelegate>

@property (nonatomic, strong) UISearchBar *searchBar;
@property (nonatomic, strong) FQDBlurView *searchBarBgView;
@property (nonatomic, strong) UITableView *searchTableView;
@property (nonatomic, strong) FQDSearchHeaderView *headerView;
@property (nonatomic, strong) FQDRefreshFooter *refreshFooter;
@property (nonatomic, strong) FQDSearchResultProvider *searchResultProvider;
@property (nonatomic, strong) UIImageView *emptyResultImageView;

@end

@implementation FQDSearchViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.view.backgroundColor = [UIColor whiteColor];
    [self setupSearchResultProvider];
    [self setupSearchBar];
    [self setupSearchTableView];
    [self setupEmptyResultImageView];
}

- (void)setupSearchResultProvider
{
    self.searchResultProvider = [[FQDSearchResultProvider alloc] init];
}

- (void)setupSearchBar
{
    self.searchBarBgView = [[FQDBlurView alloc] init];
    [self.view addSubview:self.searchBarBgView];
    
    WeakSelf;
    [self.searchBarBgView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.left.and.right.equalTo(weakSelf.view);
        make.height.equalTo(@64);
    }];
    
    UISearchBar *searchBar = [[UISearchBar alloc] init];
    searchBar.barStyle = UIBarStyleDefault;
    searchBar.translucent = YES;
    searchBar.tintColor = FQDHighlightColor;
    searchBar.backgroundImage = [UIImage new];
    searchBar.placeholder = @" 搜索";
    [self.searchBarBgView addSubview:searchBar];
    
    self.searchBar = searchBar;
    searchBar.showsCancelButton = YES;
    searchBar.delegate = self;
    searchBar.returnKeyType = UIReturnKeySearch;
    [searchBar becomeFirstResponder];
    
    // 单独设置SearchBar的CancelButton的颜色
    NSDictionary *cancelTitleAttributes = @{
        NSForegroundColorAttributeName : [UIColor whiteColor],
    };
    [[UIBarButtonItem appearanceWhenContainedIn:[UISearchBar class], nil] setTitleTextAttributes:cancelTitleAttributes forState:UIControlStateNormal];
    [[UIBarButtonItem appearanceWhenContainedIn:[UISearchBar class], nil] setTitleTextAttributes:cancelTitleAttributes forState:UIControlStateHighlighted];
    
    [searchBar mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(weakSelf.searchBarBgView).offset(20);
        make.left.equalTo(weakSelf.searchBarBgView).offset(10);
        make.right.equalTo(weakSelf.searchBarBgView).offset(-5);
    }];
}

- (void)setupSearchTableView
{
    self.searchTableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStylePlain];
    self.searchTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.searchTableView.rowHeight = 115.0f;
    self.searchTableView.dataSource = self;
    self.searchTableView.delegate = self;
    [self.view addSubview:self.searchTableView];
    
    [self.searchTableView registerClass:[FQDSearchResultTableViewCell class]
                 forCellReuseIdentifier:[FQDSearchResultTableViewCell reuseId]];
    
    WeakSelf;
    [self.searchTableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(weakSelf.searchBarBgView.mas_bottom);
        make.left.right.and.bottom.equalTo(weakSelf.view);
    }];
    
    
    FQDRefreshFooter *footer = [FQDRefreshFooter footerWithRefreshingTarget:self
                                refreshingAction:@selector(loadMoreSearchResults:)];
    self.searchTableView.mj_footer = footer;
    self.refreshFooter = footer;
}

- (void)setupEmptyResultImageView
{
    UIImage *emptyResultImage = [UIImage imageNamed:@"Explore_Search_NoResult"];
    self.emptyResultImageView = [[UIImageView alloc] initWithImage:emptyResultImage];
    self.emptyResultImageView.contentMode = UIViewContentModeCenter;
    self.emptyResultImageView.frame = self.view.bounds;
    self.emptyResultImageView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
    self.emptyResultImageView.hidden = YES;
    [self.view addSubview:self.emptyResultImageView];
}

- (void)refreshTableHeaderView
{
    NSInteger resultCount = self.searchResultProvider.totalNumber;
    NSString *resultString = [NSString stringWithFormat:@"(%@条搜索结果)", @(resultCount)];
    self.headerView.resultLabel.text = resultString;
}

- (void)refreshSearchResult:(BOOL)loadSucess
{
    if (self.searchResultProvider.totalNumber <= 0) {
        self.emptyResultImageView.hidden = NO;
        self.searchTableView.hidden = YES;
    } else {
        self.emptyResultImageView.hidden = YES;
        self.searchTableView.hidden = NO;
        [self.searchTableView reloadData];
        
        if (loadSucess) {
            [self refreshTableHeaderView];
        }
    }
}

- (UIStatusBarStyle)preferredStatusBarStyle
{
    return UIStatusBarStyleLightContent;
}

#pragma mark - Getters and Setters
- (FQDSearchHeaderView *)headerView
{
    if (!_headerView) {
        CGRect headerFrame = CGRectMake(0, 0, self.view.bounds.size.width, 50.0f);
        _headerView = [[FQDSearchHeaderView alloc] initWithFrame:headerFrame];
        self.searchTableView.tableHeaderView = _headerView;
    }
    return _headerView;
}

#pragma mark - Event response
- (void)loadNewSearchResults
{
    WeakSelf;
    [self.searchResultProvider loadNewCellItems:^(BOOL isSuccess) {
        [weakSelf.refreshFooter endRefreshing];
        [self refreshSearchResult:isSuccess];
    }];
}

- (void)loadMoreSearchResults:(id)sender
{
    WeakSelf;
    if ([self.searchResultProvider hasMoreCellItems]) {
        [self.searchResultProvider loadMoreCellItems:^(BOOL isSuccess) {
            [weakSelf.refreshFooter endRefreshing];
            [self refreshSearchResult:isSuccess];
        }];
    } else {
        [weakSelf.refreshFooter endRefreshingWithNoMoreData];
    }
}

#pragma mark - UISearchBarDelegate
- (void)searchBarCancelButtonClicked:(UISearchBar *)searchBar
{
    [self.searchBar endEditing:YES];
    [self dismissViewControllerAnimated:YES completion:nil];
}

- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar
{
    NSString *searchText = [searchBar.text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
    if (searchText.length <= 0) {
        return;
    }
    
    NSString *keyWord = [searchBar.text stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    self.searchResultProvider.keyWord = keyWord;
    
    [self loadNewSearchResults];
    
    [self.searchBar endEditing:YES];
}

#pragma mark - UIScrollViewDelegate
- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView
{
    [self.searchBar endEditing:YES];
}

#pragma mark - UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [self.searchResultProvider.cellItems count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    FQDSearchResultTableViewCell *cell = (FQDSearchResultTableViewCell *)
    [tableView dequeueReusableCellWithIdentifier:[FQDSearchResultTableViewCell reuseId]];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    cell.searchResult = self.searchResultProvider.cellItems[indexPath.row];
    return cell;
}

#pragma mark - UITableViewDelegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    FQDSearchResult *result = self.searchResultProvider.cellItems[indexPath.row];
    if (result) {
        FQDPost *post = result.post;
        FQDFeed *feed = [[FQDFeed alloc] init];
        feed.post = post;
        
        UIViewController *presentVC = nil;
        if (post.genre == FQDPostGenreVote) {
            FQDLabVoteDetailViewController *lvdVC = [[FQDLabVoteDetailViewController alloc] init];
            FQDLabFeedCellItem *feedCellItem = [FQDLabFeedCellItem cellItemWithRestModel:feed];
            feedCellItem.showSubscription = NO;
            lvdVC.labFeedCellItem = feedCellItem;
            presentVC = lvdVC;
        } else if (post.genre == FQDPostGenreOpinion) {
            FQDLabOpinionViewController *loVC = [[FQDLabOpinionViewController alloc] init];
            FQDLabFeedCellItem *feedCellItem = [FQDLabFeedCellItem cellItemWithRestModel:feed];
            feedCellItem.showSubscription = NO;
            loVC.labFeedCellItem = feedCellItem;
            presentVC = loVC;
        } else {
            FQDArticleDetailViewController *adVC = [[FQDArticleDetailViewController alloc] init];
            adVC.post = post;
            presentVC = adVC;
        }
        [self.navigationController pushViewController:presentVC animated:YES];
    }
}

@end
